package com.vvlive.caibao.smartcity.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.bean.AddMeetingBean;
import com.vvlive.caibao.smartcity.bean.MeetingByMonth;
import com.vvlive.caibao.smartcity.bean.PersonalMeetingBean;
import com.vvlive.caibao.smartcity.bean.User;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhj on 2015/9/7.
 * <p/>
 * 会议的操作
 * VAR1 http://192.168.0.114/hqs/
 * VAR2 ipadjson!ipadJson.action?op
 * <p/>
 * <p/>
 * http://192.168.0.115:8080/hqs/ipadjson!ipadJson.action?op=hqs_dept&userid=888&password=888
 * // login
 * http://192.168.0.114/hqs/ipadjson!ipadJson.action?op=hqs_login&userid=888&password=888
 */
public class MeetingsController {

    private static final String IP_AND_PORT = "http://192.168.0.114/";

    private static final String HTTP_URL_BASE = IP_AND_PORT + "hqs/";
    private static final String URL_AFTER_BASE = "ipadjson!ipadJson.action?op=";

    private KJHttp mHttp;
    private String userid;
    private String password;


    public MeetingsController() {
        mHttp = new KJHttp();
    }

    private class AsyncHttpRequest extends AsyncTask<String, Void, byte[]> {

        private HashMap<String, String> mParams;
        private HttpCallBack mHttpCallBack;

        public AsyncHttpRequest(HashMap<String, String> params, HttpCallBack callBack) {
            mParams = params;
            mHttpCallBack = callBack;
        }

        @Override
        protected byte[] doInBackground(String... params) {
            try {
                HttpURLConnection conn = (HttpURLConnection) new URL(params[0]).openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.getOutputStream().write(getParamsString(mParams).getBytes());
                if (conn.getResponseCode() == 200) {
                    return toByteArray(conn.getInputStream());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 获取post请求的参数字符串
         *
         * @param params
         * @return
         */
        private String getParamsString(HashMap<String, String> params) {
            StringBuilder builder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.append(entry.getKey());
                builder.append("=");
                builder.append(entry.getValue());
                builder.append("&");
            }
            builder.deleteCharAt(builder.length() - 1);
            return builder.toString();
        }

        /**
         * 读取输入流中的数据到byte数组
         *
         * @param stream
         * @return
         * @throws IOException
         */
        private byte[] toByteArray(InputStream stream) throws IOException {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = stream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            stream.close();
            return outputStream.toByteArray();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            if (mHttpCallBack != null) {
                if (bytes != null) {
                    mHttpCallBack.onSuccess(bytes);
                } else {
                    mHttpCallBack.onFailure(0, "Http Error");
                }
            }
        }
    }

    /**
     * 登录（USER_OK, USER_ERROR）
     *
     * @param userid
     * @param password
     * @param callBack
     */
    public void login(String userid, String password, HttpCallBack callBack) {
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_login&userid=" + userid + "&password=" + password;
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 修改密码
     *
     * @param userid
     * @param password
     * @param newpassword
     * @param callBack
     */
    public void updatePassword(String userid, String password, String newpassword, HttpCallBack callBack) {
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_updatepassword&userid=" + userid + "&password=" + password + "&newpassword=" + newpassword;
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 添加会议
     *
     * @param bean
     * @param callBack
     */
    public void addMeeting(AddMeetingBean bean, HttpCallBack callBack) {
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_addemeeting&model=hqs_add";
        HashMap<String, String> params = new HashMap<>();
        params.put("cycleop", "0");
        params.put("userid", bean.getUserid());
        params.put("password", bean.getPassword());
        params.put("meeting_room_id", bean.getMeeting_room_id());
        params.put("meeting_roomname", bean.getMeeting_roomname());
        params.put("meeting_time", bean.getMeeting_time());
        params.put("meeting_time2", bean.getMeeting_time2());
        params.put("starttime", bean.getStarttime());
        params.put("endtime", bean.getEndtime());
        params.put("meeting_name", bean.getMeeting_name());
        new AsyncHttpRequest(params, callBack).execute(url);
    }

    /**
     * 获得所有会议室内容
     *
     * @param callBack
     */
    public void fetchMeetingRooms(HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_self_meetingroom&userid=" + userid + "&password=" + password;
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 获得所有的部门
     *
     * @param callBack
     */
    public void fetchDepartments(HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_dept&userid=" + userid + "&password=" + password;
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 获取个人预定的会议
     *
     * @param callBack
     */
    public void fetchMyMeetings(HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_self_meeting&userid=" + userid + "&password=" + password;
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 根据月获取会议信息
     *
     * @param year     年
     * @param month    月
     * @param callBack
     */
    public void fetchMeetingsByMonth(int year, int month, HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE +
                             "hqs_month_meeting&userid=" + userid + "&password=" + password
                             + "&month=" + year + "-" + month;
        Log.i("GBK", url);
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 更新会议
     *
     * @param meetingBean
     * @param callBack
     */
    public void updateMeetings(MeetingByMonth meetingBean, HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE + "hqs_updatemeeting&model=hqs_update";
        HashMap<String, String> params = new HashMap<>();
        params.put("meetingid", meetingBean.getMeetingid());
        params.put("userid", userid);
        params.put("password", password);
        params.put("meeting_room_id", meetingBean.getRoomid());
        params.put("meeting_roomname", meetingBean.getRoom());
        params.put("meeting_name", meetingBean.getTopic());
        String time = meetingBean.getTime();
        params.put("meeting_time", getStartDate(time));
        params.put("meeting_time2", getEndDate(time));
        params.put("starttime", getStartTime(time));
        params.put("endtime", getEndTime(time));
        params.put("iscycle", "0");
        new AsyncHttpRequest(params, callBack).execute(url);
    }

    /**
     * 获得会议开始日期 yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public static String getStartDate(String time) {
        return time.split(" ")[0].split("_")[0];
    }

    /**
     * 获得会议结束日期 yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public static String getEndDate(String time) {
        return time.split(" ")[0].split("_")[1];
    }

    /**
     * 获得会议开始时间 HH:mm
     *
     * @param time
     * @return
     */
    public static String getStartTime(String time) {
        return time.split(" ")[1].split("-")[0];
    }

    /**
     * 获得会议结束时间 HH:mm
     *
     * @param time
     * @return
     */
    public static String getEndTime(String time) {
        return time.split(" ")[1].split("-")[1];
    }

    /**
     * 获得会议开始时间 yyyy-MM-dd HH:mm
     *
     * @param time
     * @return
     */
    public static String getStartDateTime(String time) {
        return getStartDate(time) + " " + getStartTime(time);
    }

    /**
     * 获得会议结束时间 yyyy-MM-dd HH:mm
     *
     * @param time yyyy-MM-dd_yyyy-MM-dd HH:mm-HH:mm
     * @return
     */
    public static String getEndDateTime(String time) {
        return getEndDate(time) + " " + getEndTime(time);
    }

    /**
     * @param dateTime yyyy-MM-dd HH:mm
     * @return
     */
    public static long getDateTimeInMillis(String dateTime) {

        String[] temp = dateTime.split(" ");
        String[] date = temp[0].split("-");
        String[] time = temp[1].split(":");

        int year = Integer.valueOf(date[0]);
        int month = Integer.valueOf(date[1]) - 1;
        int day = Integer.valueOf(date[2]);

        int hour = Integer.valueOf(time[0]);
        int minute = Integer.valueOf(time[1]);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day, hour, minute);

        return calendar.getTimeInMillis();
    }

    /**
     * @param time
     * @return
     */
    public static long getStartDateTimeInMillis(String time) {
        return getDateTimeInMillis(getStartDateTime(time));
    }

    /**
     * @param time
     * @return
     */
    public static long getEndDateTimeInMillis(String time) {
        return getDateTimeInMillis(getEndDateTime(time));
    }


    /**
     * 删除会议
     *
     * @param meetingid
     * @param callBack
     */
    public void deleteMeeting(String meetingid, HttpCallBack callBack) {
        User user = SmartCityApp.currentUser;
        userid = user.getUsername();
        password = user.getObjectId();
        String url = HTTP_URL_BASE + URL_AFTER_BASE +
                             "hqs_delmeeting&userid=" + userid + "&password=" + password + "&iscycle=0&meetingid=" + meetingid + "&model=hqs_delete";
        mHttp.get(url, null, false, callBack);
    }

    /**
     * 排序
     */
    public static final class Sort {

        /**
         * 按照开始时间排序
         *
         * @param beans
         */
        public static void orderByStartTimeAsc(List<PersonalMeetingBean> beans) {
            sort(beans, new Comparator<PersonalMeetingBean>() {
                @Override
                public int compare(PersonalMeetingBean lhs, PersonalMeetingBean rhs) {
                    return (int) (getStartDateTimeInMillis(lhs.getTime()) - getStartDateTimeInMillis(rhs.getTime()));
                }
            });
        }

        /**
         * 按照开始时间倒序
         *
         * @param beans
         */
        public static void orderByStartTimeDesc(List<PersonalMeetingBean> beans) {
            sort(beans, new Comparator<PersonalMeetingBean>() {
                @Override
                public int compare(PersonalMeetingBean lhs, PersonalMeetingBean rhs) {
                    return getStartDateTimeInMillis(lhs.getTime()) > getStartDateTimeInMillis(rhs.getTime()) ? -1 : 1;
                }
            });
        }

        public static void orderByStartTimeDesc2(List<MeetingByMonth> beans) {
            _sort(beans, new Comparator<MeetingByMonth>() {
                @Override
                public int compare(MeetingByMonth lhs, MeetingByMonth rhs) {
                    return getStartDateTimeInMillis(lhs.getTime()) > getStartDateTimeInMillis(rhs.getTime()) ? -1 : 1;
                }
            });
        }

        /**
         * 按照结束时间排序
         *
         * @param beans
         */
        public static void orderByEndTimeAsc(List<PersonalMeetingBean> beans) {
            sort(beans, new Comparator<PersonalMeetingBean>() {
                @Override
                public int compare(PersonalMeetingBean lhs, PersonalMeetingBean rhs) {
                    return getEndDateTimeInMillis(lhs.getTime()) > getEndDateTimeInMillis(rhs.getTime()) ? 1 : -1;
                }
            });
        }

        /**
         * 按照结束时间倒序
         *
         * @param beans
         */
        public static void orderByEndTimeDesc(List<PersonalMeetingBean> beans) {
            sort(beans, new Comparator<PersonalMeetingBean>() {
                @Override
                public int compare(PersonalMeetingBean lhs, PersonalMeetingBean rhs) {
                    return getEndDateTimeInMillis(lhs.getTime()) > getEndDateTimeInMillis(rhs.getTime()) ? -1 : 1;
                }
            });
        }

        /**
         * 排序
         *
         * @param beans
         * @param c
         */
        public static void sort(List<PersonalMeetingBean> beans, Comparator c) {
            final int size = beans.size();
            PersonalMeetingBean[] temp = new PersonalMeetingBean[size];
            for (int i = 0; i < size; i++) {
                temp[i] = beans.get(i);
            }
            Arrays.sort(temp, 0, size, c);
            beans.clear();
            for (PersonalMeetingBean obj : temp) {
                beans.add(obj);
            }
        }

        /**
         * @param list
         * @param c
         * @param <T>
         */
        public static <T> void _sort(List<T> list, Comparator<T> c) {
            final int size = list.size();
            T[] temp = (T[]) new Object[size];
            for (int i = 0; i < size; i++) {
                temp[i] = list.get(i);
            }
            Arrays.sort(temp, 0, size, c);
            list.clear();
            for (T t : temp) {
                list.add(t);
            }
        }

    }

}
